#include "stdafx.h"
#include "RadarGeode.h"
#include <cmath>

RadarGeode::RadarGeode(double lat, double lon, double range, int circleCount, int lineCount) :
	_lat(lat),
	_lon(lon),
	_range(range),
	_circleCount(circleCount),
	_lineCount(lineCount)
{
	createLines();
	createCircles();
}

RadarGeode::~RadarGeode(void)
{
}

void RadarGeode::createCircles()
{
	double rangeForEveryCircle = _range;
	double diffRange = _range / _circleCount;
	for (int i = 0; i < _circleCount; i++)
	{
		createOneCircle(_lat, _lon, rangeForEveryCircle);
		rangeForEveryCircle -= diffRange;
	}
}

void RadarGeode::createLines()
{
	Geometry* geom = new Geometry;

	Vec3Array* vertexArray = new Vec3Array;

	double centerX, centerY;
	SceneCenter::inst()->LLToXY(_lat, _lon, centerX, centerY);
	Vec3 center(centerX, centerY, 0);

	double alpha = osg::PI_2;
	double diffAlpha = 2 * osg::PI / _lineCount;
	for (int i = 0; i < _lineCount; i++)
	{
		vertexArray->push_back(center);

		double x = _range * cos(alpha) + _lat;
		double y = _range * sin(alpha) + _lon;

		double projX, projY;
		SceneCenter::inst()->LLToXY(x, y, projX, projY);

		Vec3 v(projX, projY, 0);
		vertexArray->push_back(v);

		alpha += diffAlpha;
	}

	geom->setVertexArray(vertexArray);

	Vec4Array* colorArray = new Vec4Array;
	colorArray->push_back(Vec4(1.0, 1.0, 1.0, 1.0));

	geom->setColorArray(colorArray);
	geom->setColorBinding(Geometry::BIND_OVERALL);

	Vec3Array* normalArray = new Vec3Array;
	normalArray->push_back(Vec3(0.0, 0.0, 1.0));

	geom->setNormalArray(normalArray);
	geom->setNormalBinding(Geometry::BIND_OVERALL);

	geom->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINE_STRIP, 0, _lineCount + _lineCount) );

	this->addDrawable(geom);
}

void RadarGeode::createOneCircle(double centerLat, double centerLon, double range)
{
	if (range < 1e-3)
	{
		return;
	}

	Geometry* geom = new Geometry;

	Vec3Array* vertexArray = new Vec3Array;

	int pointCount = (range < 10) ? 30 : (int)(3 * range);

	double alpha = osg::PI_2;
	double diffAlpha = 2 * osg::PI / pointCount;
	for (int i = 0; i < pointCount; i++)
	{
		double x = range * cos(alpha) + centerLat;
		double y = range * sin(alpha) + centerLon;

		double projX, projY;
		SceneCenter::inst()->LLToXY(x, y, projX, projY);

		Vec3 v(projX, projY, 0);
		vertexArray->push_back(v);

		alpha += diffAlpha;
	}

	geom->setVertexArray(vertexArray);

	Vec4Array* colorArray = new Vec4Array;
	colorArray->push_back(Vec4(1.0, 1.0, 1.0, 1.0));

	geom->setColorArray(colorArray);
	geom->setColorBinding(Geometry::BIND_OVERALL);

	Vec3Array* normalArray = new Vec3Array;
	normalArray->push_back(Vec3(0.0, 0.0, 1.0));

	geom->setNormalArray(normalArray);
	geom->setNormalBinding(Geometry::BIND_OVERALL);

	geom->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINE_LOOP, 0, pointCount) );

	this->addDrawable(geom);
}
